package com.aiden.app.common.view.banner.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.aiden.app.common.base.BaseRecyclerViewAdapter

class CTAdapter<T>(private var creator: CTViewHolderCreator<T>, private var datas: MutableList<T>, var canLoop: Boolean = true) : RecyclerView.Adapter<Holder<T>>() {

    private var onItemClickListener: BaseRecyclerViewAdapter.OnItemClickListener ?= null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder<T> {
        val layoutId = creator.getLayoutId()
        val itemView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        return creator.createHolder(itemView)
    }

    override fun getItemCount(): Int {
        if (datas.isEmpty()) return 0

        return if (canLoop) 3 * datas.size else datas.size
    }

    override fun onBindViewHolder(holder: Holder<T>, position: Int) {

        val realPosition = position % datas.size
        holder.updateUI(datas[realPosition])
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener {
                onItemClickListener?.onItemClick(holder.itemView, realPosition)
            }
        }
    }

    fun getRealItemCount(): Int = datas.size

    fun setOnItemClickListener(onItemClickListener: BaseRecyclerViewAdapter.OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }
}